package com.JavaWeb.servlet.user;

import com.JavaWeb.pojo.User;
import com.JavaWeb.service.user.UserService;
import com.JavaWeb.service.user.UserServiceImpl;
import com.JavaWeb.util.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginServlet extends HttpServlet {
    //Servlet：控制层，调用业务层代码
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        System.out.println("LoginServlet--start...");
       // request.getParameter()方法:
        // 1.获取通过http协议提交过来的数据.通过容器的实现来取得通过get或者post方式提交过来的数据
       // 2.request.getParameter()方法传递的数据，会从web客户端传到web服务器端，代表HTTP请求数据，该方法返回String类型的数据
        //获取用户名和密码
        String userCode=req.getParameter("userCode");
        String userPassword=req.getParameter("userPassword");

        //和数据库中的密码进行对比，调用业务层(调用UserService接口，使用实现接口的UserServiceImpl)
        UserService userService = new UserServiceImpl();
        User user = userService.login(userCode, userPassword);//传值查询
        System.out.println(user);
        if (user!=null){//查询用户存在
            //将用户的信息放在Session中
            req.getSession().setAttribute(Constants.USER_SESSION,user);
            //跳转到主页
            resp.sendRedirect(req.getContextPath()+"/jsp/frame.jsp");
        }
        else{//查无此人，无法登录
            //转发回登录页面，顺带提示它，用户名或者密码错误
            req.setAttribute("error","用户名或者密码错误");
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
        }

    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
